package com.qsi.app.golf.view.validation;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.qsi.app.golf.model.Golfer;
import com.qsi.app.golf.model.GolfManager;

public class GolferAdminValidator implements Validator {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	private GolfManager manager;

	public boolean supports(Class clazz) {
		return clazz.equals(Golfer.class);
	}

	public void validate(Object obj, Errors errors) {
		Golfer golfer = (Golfer) obj;
		if (golfer == null) {
			errors.rejectValue("trip", "error.not-specified", null,
					"Value required.");
			return;
		}
		logger.info("Validating with " + golfer + ": " + golfer.getFirstName() + golfer.getLastName());
		if (golfer.getFirstName() == null) {
			errors.rejectValue("firstName", "error.not-specified", null,
					"Value required.");
			return;
		}
		if (golfer.getLastName() == null) {
			errors.rejectValue("lastName", "error.not-specified", null,
					"Value required.");
			return;
		}
		List golfers = manager.getGolfers();
		if (golfers != null && !golfers.isEmpty()) {
			Iterator golfersIter = golfers.iterator();
			Golfer tempGolfer = null;
			String fullName = null;
			while (golfersIter.hasNext()) {
				tempGolfer = (Golfer)golfersIter.next();
				fullName = golfer.getFirstName() + golfer.getLastName();
				if (fullName.equals(tempGolfer.getFirstName() + tempGolfer.getLastName())) {
					errors.rejectValue("golferName", "typeMismatch", null,
					"Value required.");
					return;
				}
			}
		}
	}

	public void setGolfManager(GolfManager manager) {
		this.manager = manager;
	}

	public GolfManager getGolfManager() {
		return manager;
	}
}
